package com.leetcode.题库;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 覃国强
 * @date 2022-02-26 20:24
 */
public class 题库_0018_四数之和 {

  static
  class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
      Arrays.sort(nums);
      List<List<Integer>> answer = new ArrayList<>();
      for (int i = 0; i < nums.length; ++i) {
        if (i > 0 && nums[i] == nums[i - 1]) {
          continue;
        }
        for (int j = i + 1; j < nums.length; ++j) {
          if (j > i + 1 && nums[j] == nums[j - 1]) {
            continue;
          }
          int left = j + 1;
          int right = nums.length - 1;
          while (left < right) {
            int sum = nums[i] + nums[j] + nums[left] + nums[right];
            if (sum == target) {
              answer.add(new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[left], nums[right])));
            }
            if (sum < target) {
              ++left;
              while (left < right && nums[left] == nums[left - 1]) {
                ++left;
              }
            } else {
              --right;
              while (left < right && nums[right] == nums[right + 1]) {
                --right;
              }
            }
          }
        }
      }

      return answer;
    }
  }

}
